package name.williamwall.buxoid;
/**
 * This software is made available under the Gnu General Public License v3
 * and has absolutely no waranty. You may change the software to suit your needs.
 * 
 * Author: William Wall, IV
 */
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;

public class ImpactList extends ListActivity {
	// menu ids
	private static final int UPDATE_ID = Menu.FIRST;
	private static final int SETTINGS_ID = Menu.FIRST + 1;
	private static final int HELP_ID = Menu.FIRST + 2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.list_impacts);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		fillData();
	}
	
	private void fillData() {
	    try {
    //		Log.d("Buxfer", "filling impact data");
    		setTitle("Buxoid: Loans");
    		Cursor c = Buxoid.mDb.fetchAllImpacts();
    		startManagingCursor(c);
    		
    		String [] from = new String [] {
    				BuxoidDb.IMPACT_ENTITY,
    				BuxoidDb.IMPACT_DESC,
    				BuxoidDb.IMPACT_BALANCE
    		};
    		
    		int [] to = new int [] {
    				R.id.row_impact_name,
    				R.id.row_impact_desc,
    				R.id.row_impact_amount
    		};
    		
    		ImpactAdapter ia = new ImpactAdapter(this, R.layout.row_impact, c, from, to);
    		setListAdapter(ia);
	    } catch (IllegalStateException e) {
            // this happens when the user starts an update and navigates away from the app
            // so just ignore it
        }
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuItem item;
		item = menu.add(0, UPDATE_ID, 1, R.string.menu_update);
		item.setIcon(android.R.drawable.ic_menu_set_as);
        
        // set settings menu item and icon
        item = menu.add(1, SETTINGS_ID, 2, R.string.menu_settings);
        item.setIcon(android.R.drawable.ic_menu_preferences);

		item = menu.add(0, HELP_ID, 3, R.string.menu_help);
		item.setIcon(android.R.drawable.ic_menu_help);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Intent i;
		switch(item.getItemId()) {
		case UPDATE_ID:
		    Buxoid.mUICallback = new Handler();
            Buxoid.mFinish = new Runnable () {
                public void run () {
                    fillData();
                }
            };
        	Buxoid.update(this);
        	return true;
        case SETTINGS_ID:
        	i = new Intent(this, EditSettings.class);
            startActivity(i);
            return true;
		case HELP_ID:
			i = new Intent(this, Help.class);
			i.putExtra("topic", "Impacts");
			this.startActivity(i);
			return true;
		}
		
		return super.onMenuItemSelected(featureId, item);
	}
}
